package com.sxds.wn.util;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.springframework.context.i18n.LocaleContextHolder;

import com.sxds.wn.IConstants;


/**
 * Date Utility Class
 * This is used to convert Strings to Dates and Timestamps
 *
 * <p>
 * <a href="DateUtil.java.html"><i>View Source</i></a>
 * </p>
 * 
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 *  Modified by <a href="mailto:dan@getrolling.com">Dan Kibler </a> 
 *   to correct time pattern. Minutes should be mm not MM
 * 	(MM is month). 
 * @version $Revision: 1.5 $ $Date: 2010/05/14 01:59:31 $
 */

/**
 * Description: <p>TimestampConverter用于转换字符串到日期，日期转换到指定格式的字符串</p>
 * Content Desc:<p>TimestampConverter用于转换字符串到日期，日期转换到指定格式的字符串<p>
 * Copy Right of Personal Tangtao 2007-2020
 * @author Andy
 * @version 1.0
 */

public class DateUtil {

    private static Logger log = Logger.getLogger(DateUtil.class);
    private static String defaultDatePattern = null;
    public static final String DATE_MASK = "yyyy-MM-dd";
    public static final String CEFTS_DATE_TIME_MASK = "yyyyMMdd-HH:mm:ss.SSS";
    public static final String DATE_TIME_MASK = "yyyy-MM-dd HH:mm:ss";
    private static final String TIME_PATTERN_MASK_1 = "HH:mm:ss";
    private static final String TIME_PATTERN_MASK_2 = "HH:mm";

    public static final Pattern DATE_PATTERN_1 = Pattern.compile("\\d{4}-\\d{2}-\\d{2}$");
    public static final Pattern DATE_PATTERN_2 = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$");
    public static final Pattern TIME_PATTERN_1 = Pattern.compile("\\d{2}:\\d{2}:\\d{2}$");
    public static final Pattern TIME_PATTERN_2 = Pattern.compile("\\d{2}:\\d{2}$");
    
    
    
    //~ Methods ================================================================

    /**
     * Return default datePattern (MM/dd/yyyy)
     * @return a string representing the date pattern on the UI
     */
    public static synchronized String getDatePattern() {
        Locale locale = LocaleContextHolder.getLocale();
        try {
            defaultDatePattern = ResourceBundle.getBundle(IConstants.BUNDLE_KEY, locale).getString("date.format");
        } catch (MissingResourceException mse) {
            defaultDatePattern = "yyyy-dd-MM";
        }
        return defaultDatePattern;
    }

    /**
     * This method attempts to convert an Oracle-formatted date
     * in the form dd-MMM-yyyy to mm/dd/yyyy.
     *
     * @param aDate date from database as a string
     * @return formatted string for the ui
     */
    public static final String getDate(Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate != null) {
            df = new SimpleDateFormat(getDatePattern());
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * This method generates a string representation of a date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param strDate a string representation of a date
     * @return a converted Date object
     * @see java.text.SimpleDateFormat
     * @throws ParseException
     */
    public static final Date convertStringToDate(String aMask, String strDate)
      throws ParseException {
        SimpleDateFormat df = null;
        Date date = null;
        df = new SimpleDateFormat(aMask);

        if (log.isDebugEnabled()) {
            log.debug("converting '" + strDate + "' to date with mask '"
                      + aMask + "'");
        }

        try {
            date = df.parse(strDate);
        } catch (ParseException pe) {
            //log.error("ParseException: " + pe);
            //throw new ParseException(pe.getMessage(), pe.getErrorOffset());
        }
        return (date);
    }

    /**
     * 将日期格式内容转换为
     * @param strDate
     * @return
     * @throws ParseException
     */
    public static final Date convertStringToCeftsDate(String strDate) throws ParseException {
    	return DateUtil.convertStringToDate(DateUtil.CEFTS_DATE_TIME_MASK,strDate);
    }
    
    /**
     * This method returns the current date time in the format:
     * MM/dd/yyyy HH:MM a
     *
     * @param theTime the current time
     * @return the current date/time
     */
    public static String getTimeNow(Date theTime) {
        return getDateTime(DateUtil.DATE_TIME_MASK, theTime);
    }

    /**
     * This method returns the current date in the format: MM/dd/yyyy
     * 
     * @return the current date
     * @throws ParseException
     */
    public static Calendar getToday() throws ParseException {
        Date today = new Date();
        SimpleDateFormat df = new SimpleDateFormat(getDatePattern());

        // This seems like quite a hack (date -> string -> date),
        // but it works ;-)
        String todayAsString = df.format(today);
        Calendar cal = new GregorianCalendar();
        cal.setTime(convertStringToDate(todayAsString));

        return cal;
    }

    /**
     * This method generates a string representation of a date's date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param aDate a date object
     * @return a formatted string representation of the date
     * 
     * @see java.text.SimpleDateFormat
     */
    public static final String getDateTime(String aMask, Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate == null) {
            log.error("aDate is null!");
        } else {
            df = new SimpleDateFormat(aMask);
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * 解析日期字符串至日期类型内容
     * @param date 日期字符串
     * @param format 与日期字符串格式匹配的格式
     * @return 解析后返回的日期
     */
    public static java.util.Date parseDate(String date, String format) {
        try {
            SimpleDateFormat formatter;
            if (null == format)
                throw new IllegalArgumentException("错误的日期格式");
            formatter = new SimpleDateFormat(format);
            ParsePosition pos = new ParsePosition(0);
            return formatter.parse(date, pos);
        } catch (Exception e) {
            throw new IllegalArgumentException("错误的日期:" + date + " " + e);
        }
    }
    
    /**
     * This method generates a string representation of a date based
     * on the System Property 'dateFormat'
     * in the format you specify on input
     * 
     * @param aDate A date to convert
     * @return a string representation of the date
     */
    public static final String convertDateToString(Date aDate) {
        return getDateTime(getDatePattern(), aDate);
    }
    
    /**
     * 
     * @param date
     * @param pattern
     * @return
     */
    public static final String convertDataToString(Date date,String pattern){
    	return getDateTime(pattern, date);
    }

    /**
     * This method converts a String to a date using the datePattern
     * 
     * @param strDate the date to convert (in format MM/dd/yyyy)
     * @return a date object
     * 
     * @throws ParseException
     */
    public static Date convertStringToDate(String strDate)
      throws ParseException {
        Date aDate = null;
        try {
            if (log.isDebugEnabled()) {
                log.debug("converting date with pattern: " + getDatePattern());
            }
            aDate = convertStringToDate(getDatePattern(), strDate);
        } catch (ParseException pe) {
            log.error("Could not convert '" + strDate
                      + "' to a date, throwing exception");
            pe.printStackTrace();
            throw new ParseException(pe.getMessage(),pe.getErrorOffset());
                    
        }
        return aDate;
    }
    
    /**
     * 解析日期字符串至日期类型内容,返回java.sql.Date日期类型数据内容
     * @param date 日期字符串
     * @param format 与日期字符串格式匹配的格式
     * @return 解析后返回的日期
     */
    public static java.sql.Date parseSqlDate(String date, String format) {
        try {
            SimpleDateFormat formatter;
            if (null == format)
                throw new IllegalArgumentException("错误的日期格式");
            formatter = new SimpleDateFormat(format);
            ParsePosition pos = new ParsePosition(0);
            java.util.Date utilDate = formatter.parse(date, pos);
            return new java.sql.Date( utilDate.getTime() );
        } catch (Exception e) {
            throw new IllegalArgumentException("错误的日期:" + date + " " + e);
        }
    }
    
    
    /**
     * 获取日期格式
     * @param date 日期字符串
     * @return 日期格式
     * @throws Exception 非法参数或不支持格式错误信息
     */
    public static String getDatePattern(String date) throws Exception{
    	if( date==null || "".equals(date) ){
    		throw new java.lang.IllegalArgumentException("非法日期参数，无法解析日期");
    	}
    	if( DateUtil.DATE_PATTERN_1.matcher(date).find() ){
			return "yyyy-MM-dd";
		}else if( DATE_PATTERN_2.matcher(date).find() ){
			return "yyyy-MM-dd HH:mm:ss";
		}else if( TIME_PATTERN_1.matcher(date).find()){
			return "HH:mm:ss";
		}else if( TIME_PATTERN_2.matcher(date).find()){
			return "HH:mm";
		}else{
			throw new Exception("未知日期格式，无法解析日期"); 
		}
    }
    
    /*
     * 获取系统时间
     */
    public static String getSystemDateTime(){
    	return DateUtil.convertDataToString(new Date(), "yyyy-MM-dd HH:mm:ss");
    }
    
    /**
     * 获取系统时间
     * @return
     */
    public static String getSystemDate(){
    	return DateUtil.convertDataToString(new Date(), "yyyy-MM-dd");
    }
    
    /**
     * 获取系统年份
     * @return
     */
    public static String getSystemYear(){
    	return DateUtil.convertDataToString(new Date(),"yyyy");
    }
    
}